<template>
  <div class="format-page">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-breadcrumb separator="/" style="margin-bottom: 20px;">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>代码格式化工具</el-breadcrumb-item>
        </el-breadcrumb>
        <h2 style="margin-bottom: 20px; color: #303133;">代码格式化工具</h2>
      </el-col>
    </el-row>

    <el-tabs v-model="activeTab" type="card">
      <!-- JSON格式化 -->
      <el-tab-pane label="JSON格式化" name="json">
        <el-card>
          <el-form :model="jsonForm" label-width="100px">
            <el-form-item label="输入JSON">
              <el-input
                v-model="jsonForm.input"
                type="textarea"
                :rows="8"
                placeholder="请输入要格式化的JSON字符串"
                @input="formatJson"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="formatJson">格式化</el-button>
              <el-button @click="compressJson">压缩</el-button>
              <el-button @click="validateJson">验证</el-button>
            </el-form-item>
            <el-form-item label="格式化结果">
              <el-input
                v-model="jsonForm.output"
                type="textarea"
                :rows="12"
                readonly
                placeholder="格式化后的JSON将在这里显示"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="copyToClipboard(jsonForm.output)">
                复制结果
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- XML格式化 -->
      <el-tab-pane label="XML格式化" name="xml">
        <el-card>
          <el-form :model="xmlForm" label-width="100px">
            <el-form-item label="输入XML">
              <el-input
                v-model="xmlForm.input"
                type="textarea"
                :rows="8"
                placeholder="请输入要格式化的XML字符串"
                @input="formatXml"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="formatXml">格式化</el-button>
              <el-button @click="compressXml">压缩</el-button>
              <el-button @click="validateXml">验证</el-button>
            </el-form-item>
            <el-form-item label="格式化结果">
              <el-input
                v-model="xmlForm.output"
                type="textarea"
                :rows="12"
                readonly
                placeholder="格式化后的XML将在这里显示"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="copyToClipboard(xmlForm.output)">
                复制结果
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- HTML格式化 -->
      <el-tab-pane label="HTML格式化" name="html">
        <el-card>
          <el-form :model="htmlForm" label-width="100px">
            <el-form-item label="输入HTML">
              <el-input
                v-model="htmlForm.input"
                type="textarea"
                :rows="8"
                placeholder="请输入要格式化的HTML字符串"
                @input="formatHtml"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="formatHtml">格式化</el-button>
              <el-button @click="compressHtml">压缩</el-button>
              <el-button @click="validateHtml">验证</el-button>
            </el-form-item>
            <el-form-item label="格式化结果">
              <el-input
                v-model="htmlForm.output"
                type="textarea"
                :rows="12"
                readonly
                placeholder="格式化后的HTML将在这里显示"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="copyToClipboard(htmlForm.output)">
                复制结果
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

const route = useRoute()
const activeTab = ref('json')

// 根据URL参数设置活动标签页
onMounted(() => {
  const tab = route.query.tab
  if (tab && ['json', 'xml', 'html'].includes(tab)) {
    activeTab.value = tab
  }
})

// JSON表单
const jsonForm = reactive({
  input: '',
  output: ''
})

// XML表单
const xmlForm = reactive({
  input: '',
  output: ''
})

// HTML表单
const htmlForm = reactive({
  input: '',
  output: ''
})

// JSON格式化
const formatJson = () => {
  if (!jsonForm.input.trim()) {
    jsonForm.output = ''
    return
  }
  
  try {
    const parsed = JSON.parse(jsonForm.input)
    jsonForm.output = JSON.stringify(parsed, null, 2)
    ElMessage.success('JSON格式化成功')
  } catch (error) {
    jsonForm.output = `JSON格式错误: ${error.message}`
    ElMessage.error('JSON格式错误')
  }
}

// JSON压缩
const compressJson = () => {
  if (!jsonForm.input.trim()) {
    jsonForm.output = ''
    return
  }
  
  try {
    const parsed = JSON.parse(jsonForm.input)
    jsonForm.output = JSON.stringify(parsed)
    ElMessage.success('JSON压缩成功')
  } catch (error) {
    jsonForm.output = `JSON格式错误: ${error.message}`
    ElMessage.error('JSON格式错误')
  }
}

// JSON验证
const validateJson = () => {
  if (!jsonForm.input.trim()) {
    ElMessage.warning('请输入JSON内容')
    return
  }
  
  try {
    JSON.parse(jsonForm.input)
    ElMessage.success('JSON格式正确')
  } catch (error) {
    ElMessage.error(`JSON格式错误: ${error.message}`)
  }
}

// XML格式化
const formatXml = () => {
  if (!xmlForm.input.trim()) {
    xmlForm.output = ''
    return
  }
  
  try {
    const formatted = formatXmlString(xmlForm.input)
    xmlForm.output = formatted
    ElMessage.success('XML格式化成功')
  } catch (error) {
    xmlForm.output = `XML格式错误: ${error.message}`
    ElMessage.error('XML格式错误')
  }
}

// XML压缩
const compressXml = () => {
  if (!xmlForm.input.trim()) {
    xmlForm.output = ''
    return
  }
  
  try {
    const compressed = xmlForm.input.replace(/\s+/g, ' ').trim()
    xmlForm.output = compressed
    ElMessage.success('XML压缩成功')
  } catch (error) {
    xmlForm.output = `XML处理错误: ${error.message}`
    ElMessage.error('XML处理错误')
  }
}

// XML验证
const validateXml = () => {
  if (!xmlForm.input.trim()) {
    ElMessage.warning('请输入XML内容')
    return
  }
  
  try {
    const parser = new DOMParser()
    const xmlDoc = parser.parseFromString(xmlForm.input, 'text/xml')
    const parseError = xmlDoc.getElementsByTagName('parsererror')
    
    if (parseError.length > 0) {
      ElMessage.error('XML格式错误')
    } else {
      ElMessage.success('XML格式正确')
    }
  } catch (error) {
    ElMessage.error(`XML验证错误: ${error.message}`)
  }
}

// HTML格式化
const formatHtml = () => {
  if (!htmlForm.input.trim()) {
    htmlForm.output = ''
    return
  }
  
  try {
    const formatted = formatHtmlString(htmlForm.input)
    htmlForm.output = formatted
    ElMessage.success('HTML格式化成功')
  } catch (error) {
    htmlForm.output = `HTML格式错误: ${error.message}`
    ElMessage.error('HTML格式错误')
  }
}

// HTML压缩
const compressHtml = () => {
  if (!htmlForm.input.trim()) {
    htmlForm.output = ''
    return
  }
  
  try {
    const compressed = htmlForm.input.replace(/\s+/g, ' ').trim()
    htmlForm.output = compressed
    ElMessage.success('HTML压缩成功')
  } catch (error) {
    htmlForm.output = `HTML处理错误: ${error.message}`
    ElMessage.error('HTML处理错误')
  }
}

// HTML验证
const validateHtml = () => {
  if (!htmlForm.input.trim()) {
    ElMessage.warning('请输入HTML内容')
    return
  }
  
  try {
    const parser = new DOMParser()
    const htmlDoc = parser.parseFromString(htmlForm.input, 'text/html')
    const parseError = htmlDoc.getElementsByTagName('parsererror')
    
    if (parseError.length > 0) {
      ElMessage.error('HTML格式错误')
    } else {
      ElMessage.success('HTML格式正确')
    }
  } catch (error) {
    ElMessage.error(`HTML验证错误: ${error.message}`)
  }
}

// XML格式化函数
const formatXmlString = (xml) => {
  let formatted = ''
  let indent = ''
  const tab = '  '
  
  xml.split(/>\s*</).forEach(node => {
    if (node.match(/^\/\w/)) {
      indent = indent.substring(tab.length)
    }
    formatted += indent + '<' + node + '>\r\n'
    if (node.match(/^<?\w[^>]*[^\/]$/)) {
      indent += tab
    }
  })
  
  return formatted.substring(1, formatted.length - 3)
}

// HTML格式化函数
const formatHtmlString = (html) => {
  let formatted = ''
  let indent = ''
  const tab = '  '
  
  // 简单的HTML格式化
  const lines = html.split(/>\s*</)
  lines.forEach((line, index) => {
    if (line.trim()) {
      if (line.startsWith('/')) {
        indent = indent.substring(tab.length)
      }
      formatted += indent + '<' + line + '>\n'
      if (!line.startsWith('/') && !line.endsWith('/')) {
        indent += tab
      }
    }
  })
  
  return formatted
}

// 复制到剪贴板
const copyToClipboard = async (text) => {
  if (!text) {
    ElMessage.warning('没有内容可复制')
    return
  }
  
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('复制成功')
  } catch (error) {
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('复制成功')
  }
}
</script>

<style scoped>
.format-page {
  max-width: 1000px;
  margin: 0 auto;
}

.el-tabs {
  margin-top: 20px;
}
</style> 